package com.baize.markwondemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.BlurMaskFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.MaskFilterSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.baize.markwondemo.spans.ClickableSpanNoUnderline;
import com.baize.markwondemo.spans.CustomHashSpan;
import com.baize.markwondemo.spans.CustomMentionSpan;
import com.baize.markwondemo.spans.MaskTextSpan;
import com.baize.markwondemo.spans.SpanClickableSpan;
import com.dodolive.app.lib.commonmark.node.Heading;
import com.dodolive.app.lib.commonmark.node.MentionLinkNode;
import com.dodolive.app.lib.commonmark.node.Node;
import com.dodolive.app.lib.commonmark.node.SoftLineBreak;
import com.dodolive.app.lib.commonmark.parser.Parser;
import com.dodolive.app.lib.markwon.core.AbstractMarkwonPlugin;
import com.dodolive.app.lib.markwon.core.BlockHandlerDef;
import com.dodolive.app.lib.markwon.core.LinkResolverDef;
import com.dodolive.app.lib.markwon.core.Markwon;
import com.dodolive.app.lib.markwon.core.MarkwonConfiguration;
import com.dodolive.app.lib.markwon.core.MarkwonVisitor;
import com.dodolive.app.lib.markwon.core.Prop;
import com.dodolive.app.lib.markwon.core.RenderProps;
import com.dodolive.app.lib.markwon.core.SpanFactory;
import com.dodolive.app.lib.markwon.core.core.spans.CodeSpan;
import com.dodolive.app.lib.markwon.core.syntax.SyntaxHighlightNoOp;
import com.dodolive.app.lib.markwon.simple_ext.SimpleExtPlugin;


import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

  public static boolean flag = false;

//    public static final String str = "**Hello word!**\n" +
//      "*abcdefg防剧透防剧透||防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透防剧透" +
//      "@白泽@ 阿斯利康大手大[百度](https://www.baidu.com)脚6||透$防剧@透防@add$asd*";
//  public static final String str = "start@测试号^_ha_^end<#103569>end2";
//  public static final String str = "star<a href=\"http://www.baidu.com\">百度</a>end";
//  public static final String str = "哈**<103569>**";
//public static final String str = "***<#103569>***";
//public static final String str = "# Markwon\n" + "JJJJJ";

  //bug文本
//  public static final String str = "||**吃吃吃吃**<#103569>||";
//  public static final String str = "吃吃吃吃||<#103569>||";
//  public static final String str = "||**吃吃吃吃**||哈哈哈哈哈||哈哈哈哈哈||";  //待修复
//  public static final String str = "||123455||<#103569>||<#103569>||";
//  public static final String str = "||123455||**<#103569>**";
//  public static final String str = "**<#103569>*<#103569>***";
//  public static final String str = "||**<#103569>**||";  //待修复
//  public static final String str = "||*<#103569>*||";  //待修复
//  public static final String str = "~~*<#103569>*~~";
//  public static final String str = "__*<#103569>*__";
  //1，
//  public static final String str = "内容内容 **<#103569>**";
//  public static final String str = "内容内容**%内容内容**";
  //2.
//  public static final String str = "**<#103569> **";
  //3.
//  public static final String str = "*<#103569>*";
  //4.
//  public static final String str = "||<#103569>||<#103569>||<#103569>||";
  //5.
//  public static final String str = "内容||<#103569>||";
  //6.待修复
//  public static final String str = "||内容**<#103569>**||";
//  public static final String str = "内容**<#103569>**";
//  public static final String str = "||**内容**||内容";
//  public static final String str = "》 haha";
//  public static final String str = "\uD83D\uDC68\uD83C\uDFFB‍\uD83D\uDE80本周幸运宇航员名单：\n\n★自选1车: \n\n<@!1791906> \n@害怕喝粥的甜系兜兜崽\uD83D\uDC38\uD83D\uDC38\uD83D\uDC38 \n@Bonnie酱酱爱喵小喵\uD83D\uDC31 \n@心儿 \n@爱吃萝卜爱吃菜\uD83D\uDC52  \n@到了没到 \n@兔哥 \n@大脸咩咩 \n@几许 \n@小笨猪咔咔 \n@幸运发光光 \n@羡入四月.\uD83C\uDF08⭕️仔仔 \n@扫地阿姨\uD83E\uDDF9柯雅吖 \n@草莓熊✨不要再输了 \n@爱宝贝 \n@Kimba  \n@皮皮 \n@Yuriii⚜️酒吧VIP \n@Gingercee \n@晓仪 \n\n★自选2车: \n\n@困困子\uD83E\uDDF8 \n@南球yoru \n@Jo\uD83D\uDC2C❁*✲ﾟ* \n@慕斯 \n\n★自选3车: \n\n@退休阿姨❄️ゆき\uD83C\uDF4E \n@彩虹岛\uD83C\uDF08莹莹 \n\n★自选4车: \n\n@rosemary \n\n\uD83D\uDD16领奖时间：\n本周日，11.20北京时间早9:00-下午13:00\n届时将开放岛内排队，大家不要错过了～\n\n⚠️领奖排队时务必备注自己是第几车. \n\n\uD83E\uDD73恭喜以上小伙伴，周末星空馆休息，下周一我们再一起旅行噢～\n";
//  public static final String str = "# 这是一级标题\n" +
//      "## 这是二级标题\n" +
//      "**这是加粗的文字**\n" +
//      "*这是倾斜的文字*`\n" +
//      "***这是斜体加粗的文字***\n" +
//      "~~这是加删除线的文字~~\n" +
//      "> 这是引用的内容\n" +
//      "---\n" +
//      "![图片alt](图片地址 ''图片title'')\n" +
//      "[超链接名](超链接地址 \"超链接title\")\n" +
//      "- 列表内容\n" +
//      "+ 列表内容\n" +
//      "* 列表内容\n" +
//      "1. 列表内容\n" +
//      "2. 列表内容\n" +
//      "   1. 列表内容\n" +
//      "表头|表头|表头\n" +
//      "---|:--:|---:\n" +
//      "内容|内容|内容\n" +
//      "内容|内容|内容\n" +
//      "`代码内容`\n" +
//      "```python\n" +
//      "  代码...\n" +
//      "  代码...\n" +
//      "  代码...\n" +
//      "```\n"
//      + "<a href=\"超链接地址\" target=\"_blank\">超链接名</a>"
//      ;
//  public static final String str = "```<@!5656> <@!5641> <@!5078> <@!4928> \n<@!5083> \n<@!5070> \n<@!4930> \n<@!5666>```";
  public static final String str = "||空军建军节||22222||立刻接受的||";


  private Markwon markwon;

  private TextView textView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.tv_text);

    markwon = Markwon.builder(App.mInstance)
//        .usePlugin(SimpleExtPlugin.create(plugin -> plugin
//            .addExtension(1, '@', new SpanFactory() {
//              @Override
//              public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
//                return new URLSpan("https://www.baidu.com");
//              }
//            })))
//        .usePlugin(new AbstractMarkwonPlugin() {
//          @Override
//          public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
//            builder.syntaxHighlight(new SyntaxHighlightNoOp());//高亮语法
//          }
//        })
        .usePlugin(new AbstractMarkwonPlugin() {

          //配置解析器解析器
//          @Override
//          public void configureParser(@NonNull Parser.Builder builder) {
//            // no need to call `super.configureParser(builder)`
//            builder.extensions(Collections.singleton(StrikethroughExtension.create()));
//          }

          //配置 在Markdown中打开链接
          @Override
          public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
            builder.linkResolver(new LinkResolverDef());
          }

          @Override
          public void configureVisitor(@NonNull MarkwonVisitor.Builder builder) {
            //配置软换行另起一行
            builder.on(SoftLineBreak.class, new MarkwonVisitor.NodeVisitor<SoftLineBreak>() {
              @Override
              public void visit(@NonNull MarkwonVisitor visitor, @NonNull SoftLineBreak softLineBreak) {
                visitor.forceNewLine();
              }
            });

            //配置MentionLinkNode
            builder.on(MentionLinkNode.class, new MarkwonVisitor.NodeVisitor<MentionLinkNode>() {
              @Override
              public void visit(@NonNull MarkwonVisitor visitor, @NonNull MentionLinkNode mentionLinkNode) {
                int length = visitor.length();
                final String literal = mentionLinkNode.getLiteral();
                visitor.builder().append(literal);
//                visitor.visitChildren(strongEmphasis);//??
                Log.i("baize_md", "visit: start:" + length + " content:" + literal);
                visitor.setSpans(length, new CustomMentionSpan(MainActivity.this, "https://www.baidu.com", true));
              }
            });

            //配置Heading样式
            builder.blockHandler(new BlockHandlerDef() {
              @Override
              public void blockEnd(@NonNull MarkwonVisitor visitor, @NonNull Node node) {
                if (node instanceof Heading) {
                  if (visitor.hasNext(node)) {
                    visitor.ensureNewLine();
                    // ensure new line but do not force insert one
                  }
                } else {
                  super.blockEnd(visitor, node);
                }
              }
            });

          }
        })
        .usePlugin(SimpleExtPlugin.create())
        .usePlugin(new AbstractMarkwonPlugin() {
          @Override
          public void configure(@NonNull Registry registry) {
            registry.require(SimpleExtPlugin.class, new Action<SimpleExtPlugin>() {
              @Override
              public void apply(@NonNull SimpleExtPlugin plugin) {
                plugin.addExtension(2, '_', new SpanFactory() {//防剧透
                  @Nullable
                  @Override
                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
                    return new UnderlineSpan();
                  }
                });
                plugin.addExtension(2, '|', new SpanFactory() {//防剧透
                  @Nullable
                  @Override
                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
                    Object objectFlag = props.get(Prop.of("spanFlag"));
                    int flag = (objectFlag instanceof Integer) ? (int) objectFlag : -1;
                    //TODO 初始状态
                    return new MaskTextSpan(flag);
                  }
                });
                plugin.addExtension(2, '~', new SpanFactory() {
                  @Nullable
                  @Override
                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
                    return new StrikethroughSpan();
                  }
                });
                plugin.addExtension(1, '`', new SpanFactory() {
                  @Nullable
                  @Override
                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
                    return new CodeSpan(configuration.theme());
                  }
                });
                plugin.addExtension(3, '`', new SpanFactory() {
                  @Nullable
                  @Override
                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
                    return new CodeSpan(configuration.theme());
                  }
                });
//                plugin.addExtension(2,'_', new SpanFactory() {
//                      @Nullable
//                      @Override
//                      public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
//                        return new UnderlineSpan();
//                      }
//                    });
//                plugin.addExtension(1, '@', new SpanFactory() {
//                  @Nullable
//                  @Override
//                  public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
//                    return new ForegroundColorSpan(Color.RED);
//                  }
//                });
              }
            });
          }
        })
        .build();

//    textView.setText(str);
//    textView.setMovementMethod(LinkMovementMethod.getInstance());//不设置点击会失效
//    textView.setHintTextColor(getResources().getColor(android.R.color.transparent));//不设置会有背景色

//    markwon.setMarkdown(textView, str);

    final Node node = markwon.parse(str);
//    printlnNode(node.getFirstChild(), 0);
    final Spanned markdown = markwon.render(node);
    markwon.setParsedMarkdown(textView, markdown);

    CharSequence mdText = textView.getText();
    textView.setMovementMethod(MentionMovementMethod.getInstance());

//    Spannable spContent = handleLinks(textView.getText());
//    applyMentionLink("https://www.bing.cn", 10, 20, spContent);

//    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(spContent);
//    spContent = spannableStringBuilder.insert(2," ");
//    textView.setText(spContent);
//    Log.i("baize", "onCreate: " + mdText);

//    textView.setText(str);
    System.out.println("baize hahahahhaah");
    matchStringByIndexOf(str, "**");
  }

  public void onResetText(View view) {
    final Node node = markwon.parse(str);
    final Spanned markdown = markwon.render(node);
    markwon.setParsedMarkdown(textView, markdown);
    textView.setMovementMethod(MentionMovementMethod.getInstance());
  }

  private void printlnNode(Node node, int index) {
    Log.i("baize_md", "printlnNode: " + node.toString() + " " + index);
    if (node.getNext() != null) {
      index++;
      printlnNode(node.getNext(), index);
    }
  }

  private Spannable handleLinks(CharSequence text) {
    Spannable sp;
    if (text instanceof Spannable) {
      sp = (Spannable) text;
    } else {
      Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance();
      sp = mSpannableFactory.newSpannable(text);
    }
    return sp;
  }

  private void applyMentionLink(String url, int start, int end, Spannable text) {
    final URLSpan span = new CustomHashSpan(this, url, true);
    text.setSpan(span, 30, 40, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//      text.setSpan(new ForegroundColorSpan(Color.parseColor("#5873F2")), 30, 40, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  }

  private void matchStringByIndexOf(String parent, String child) {
    int count = 0;
    int index = 0;
    while ((index = parent.indexOf(child, index)) != -1) {
      index = index + child.length();
      count++;
    }
    System.out.println("匹配个数为" + count);                //结果输出
  }

}